package mvc.action;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mvc.config.ConfigFileReader;

public class ActionServlet extends HttpServlet {

	private static final long serialVersionUID = 3004287391687650829L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//设置字符格式
		request.setCharacterEncoding("GBK");
		response.setCharacterEncoding("GBK");
		String action = request.getServletPath();
		ServletContext context = this.getServletContext();
		Map<String, String[]> map = (Map<String, String[]>) context.getAttribute("mvc");
		String[] values = map.get(action);
		String className = values[0];
		String methodName = values[1];
		String[] parasName = values[2].split(",");
		Class[] paras = new Class[parasName.length];
		for(int i = 0; i < parasName.length;i++){
			try {
				paras[i] = Class.forName(parasName[i]);
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
		try {
			Class clazz = Class.forName(className);
			Object controller = clazz.newInstance();
			Method method = clazz.getDeclaredMethod(methodName, paras);//获取方法

			Object[] parasInstaces = new Object[paras.length];
			for (int i = 0; i < paras.length; i++) {
				//装配方法参数

				Object paraInstance = ConfigFileReader.getFormInfo(paras[i], request);
				parasInstaces[i] = paraInstance;
			}
			//执行方法
			method.invoke(controller, parasInstaces).toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		//指明跳转地址
		RequestDispatcher dis = request.getRequestDispatcher("/index.jsp");
		//执行跳转
		dis.forward(request, response);		
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//转入同一个方法中处理
		this.doGet(request, response);
	}

}
